import React from 'react';
import {Spin, Card, Button, Table, Row, Col} from 'antd';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
import PropTypes from 'prop-types';
import {transportType, partOrderPriceTerms, paymentType, currency, proformaInvoiceStatus} from '../Enum';
import routes from './routes';
import {DATETIME_FORMAT, TABLE, FILES_API} from '../constants';
import {PERMISSION, formatPrintExcelUrl, formatPrintPdfUrl} from './constants';
import {conventEnumValueToString, formatDateTime, formatAmount} from '../utils';
import {getDetail, abandonData, cancelData} from './api';
import {injectIntl} from './intl';
import {hasPermissions} from './utils';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import styles from './style.css';
const {Description} = DescriptionList;
const basePath = fetch.basePath || '';
const url = '/#/dcs/parts/stockRequirement/add';
class DetailPanel extends React.PureComponent {
    state = {
        isFetching: false,
        data: {},
        details: [],
        partSaleOrder: {}
    }
    componentDidMount() {
        this.getDetailInfo();
    }
    getDetailInfo = () => {
        const id = this.props.id;
        this.setState({isFetching: true});
        getDetail(id)
            .then(res => {
                if(res.ok)
                    this.setState({
                        isFetching: false,
                        data: res.data,
                        details: res.data.details.map(d => Object.assign({}, d, {
                            order: res.data.details.findIndex(x => x.partId === d.partId) + 1,
                        })),
                        partSaleOrder: res.data.partSaleOrder
                    });
                else
                    this.setState(({
                        isFetching: false
                    }));
            });
    }
    // eslint-disable-next-line react/sort-comp
    onCancel = () => {
        this.props.history.push(routes.query.url());
    }
    onClickAbandon = () => {
        this.setState({loading: true});
        const data = {
            rowVersion: this.state.data.rowVersion
        };
        abandonData(this.state.data.id, data)
            .then(res => {
                this.setState({loading: false});
                if(res.ok)
                    this.props.successReturn();
            });
    }
    onClickCancel = () => {
        this.setState({loading: true});
        const data = {
            rowVersion: this.state.data.rowVersion
        };
        cancelData(this.state.data.id, data)
            .then(res => {
                this.setState({loading: false});
                if(res.ok)
                    this.props.successReturn();
            });
    }
    onPrintExcel = e => {
        e.stopPropagation();
        window.open(formatPrintExcelUrl(this.props.id, e.currentTarget.dataset.code));
    }
    onPrintPdf = e => {
        e.stopPropagation();
        window.open(formatPrintPdfUrl(this.props.id, e.currentTarget.dataset.code));
    }
    setRowClassName(record) {
        if(record.price && record.isEstimated)
            return styles.rowStyle;
    }
    render() {
        const {data, partSaleOrder} = this.state;
        const {attachments = []} = data;
        const {formatMessage} = this.props.intl;
        const operations = [];
        let totalAmount = 0;
        let totalQuantity = 0;
        if(this.state.details)
            this.state.details.forEach(d => {
                totalAmount += (d.amount);
                totalQuantity += (d.quantity);
            });
        if(hasPermissions(this.props.permissions, PERMISSION.update) && hasPermissions(data.options, PERMISSION.update))
            operations.push(<Button key="update" href={`#${routes.update.format(this.props.id)}`} size="small">{
                formatMessage({
                    id: 'detailPanel.update',
                    defaultMessage: '编辑'
                })
            }</Button>);
        if(hasPermissions(this.props.permissions, PERMISSION.confirm) && hasPermissions(data.options, PERMISSION.confirm))
            operations.push(<Button key="confirm" href={`#${routes.confirm.format(this.props.id)}`} size="small">{
                formatMessage({
                    id: 'detailPanel.confirm',
                    defaultMessage: '确认'
                })
            }</Button>);
        if(hasPermissions(this.props.permissions, PERMISSION.audit) && hasPermissions(data.options, PERMISSION.audit))
            operations.push(<Button key="audit" href={`#${routes.audit.format(this.props.id)}`} size="small">{
                formatMessage({
                    id: 'detailPanel.audit',
                    defaultMessage: '资金审核'
                })
            }</Button>);
        if(hasPermissions(this.props.permissions, PERMISSION.create) && hasPermissions(data.options, PERMISSION.create))
            operations.push(<Button key="create" href={`${basePath}${url}?partSaleOrderId=${partSaleOrder.id}`} target="_blank" size="small">{
                formatMessage({
                    id: 'detailPanel.create',
                    defaultMessage: '生成备货需求'
                })
            }</Button>);
        if(hasPermissions(this.props.permissions, PERMISSION.abandon) && hasPermissions(data.options, PERMISSION.abandon))
            operations.push(<WrappedPopconfirm
                key="abandon"
                id={this.props.id}
                placement="topLeft"
                onConfirm={this.onClickAbandon}
                title={formatMessage({
                    id: 'detailPanel.validate.abandon',
                    defaultMessage: '是否确认作废？'
                })}>
                <Button key="abandon" size="small">{
                    formatMessage({
                        id: 'detailPanel.abandon',
                        defaultMessage: '作废'
                    })
                }</Button>
            </WrappedPopconfirm>);
        if(hasPermissions(this.props.permissions, PERMISSION.cancel) && hasPermissions(data.options, PERMISSION.cancel))
            operations.push(<WrappedPopconfirm
                key="cancel"
                id={this.props.id}
                placement="topLeft"
                onConfirm={this.onClickCancel}
                title={formatMessage({
                    id: 'detailPanel.validate.cancel',
                    defaultMessage: '是否确认取消订单'
                })}>
                <Button key="cancel" size="small">{
                    formatMessage({
                        id: 'detailPanel.cancel',
                        defaultMessage: '取消'
                    })
                }</Button>
            </WrappedPopconfirm>);
        if(hasPermissions(this.props.permissions, PERMISSION.printExcel) && hasPermissions(data.options, PERMISSION.printExcel))
            operations.push(
                <Button key="printExcel" data-code={partSaleOrder.code} onClick={this.onPrintExcel} size="small">
                    {formatMessage({
                        id: 'detail.btn.printExcel',
                        defaultMessage: '打印Excel'
                    })}
                </Button>
            );
        if(hasPermissions(this.props.permissions, PERMISSION.printPdf) && hasPermissions(data.options, PERMISSION.printPdf))
            operations.push(
                <Button key="printPdf" data-code={partSaleOrder.code} onClick={this.onPrintPdf} size="small">
                    {formatMessage({
                        id: 'detail.btn.printPdf',
                        defaultMessage: '打印PDF'
                    })}
                </Button>
            );
        const colums = [{
            title: formatMessage({
                id: 'detailPanel.column.order',
                defaultMessage: '序号'
            }),
            dataIndex: 'order',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.partCode',
                defaultMessage: '备件编号'
            }),
            width: 100,
            dataIndex: 'partCode',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.partName',
                defaultMessage: '备件名称'
            }),
            width: 200,
            dataIndex: 'partName',
            render: text => <div title={text} className={styles.partBtn}>{text}</div>
        }, {
            title: formatMessage({
                id: 'detailPanel.column.quantity',
                defaultMessage: '订购数量'
            }),
            dataIndex: 'quantity'
        }, {
            title: formatMessage({
                id: 'detailPanel.column.price',
                defaultMessage: '单价'
            }),
            dataIndex: 'price',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.amount',
                defaultMessage: '金额'
            }),
            dataIndex: 'amount',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.newPartCode',
                defaultMessage: '被替换件编号'
            }),
            dataIndex: 'newPartCode'
        }];
        const operateHisColums = [{
            title: formatMessage({
                id: 'detailPanel.column.operatorName',
                defaultMessage: '操作人'
            }),
            dataIndex: 'operatorName',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.operateStatus',
                defaultMessage: '操作状态'
            }),
            dataIndex: 'operateStatus',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.operateTime',
                defaultMessage: '操作时间'
            }),
            dataIndex: 'operateTime',
            render: text => formatDateTime(text, DATETIME_FORMAT)
        }];
        return (
            <div>
                <Spin spinning={this.state.isFetching}>
                    <Card>
                        <DescriptionList size="large" title={<Row><Col span={6}>{
                            formatMessage({
                                id: 'detailPanel.card.partOtherOrder',
                                defaultMessage: '订单信息'
                            })
                        }</Col>
                        <Col className={`col-align-right ${styles.detail}`} span={18}>{operations}</Col></Row>}>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.dealerCode',
                                defaultMessage: '总代号'
                            })}>{partSaleOrder.dealerCode}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.submitTime',
                                defaultMessage: '提报日期'
                            })}>{formatDateTime(partSaleOrder.submitTime, DATETIME_FORMAT)}</Description>
                            <Description term={formatMessage({
                                id: 'detail.operation.country',
                                defaultMessage: '国家/地区'
                            })}>{partSaleOrder.country}</Description>
                            <Description term={formatMessage({
                                id: 'detail.operation.code',
                                defaultMessage: '备件订单号'
                            })}>{partSaleOrder.code}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.partOrderType',
                                defaultMessage: '订单类型'
                            })}>{partSaleOrder.partOrderTypeName}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.paymentType',
                                defaultMessage: '付款方式'
                            })}>{conventEnumValueToString(paymentType, partSaleOrder.paymentType)}</Description>
                            <Description term={formatMessage({
                                id: 'detail.operation.customerOrderCode',
                                defaultMessage: '客户订单号'
                            })}>{partSaleOrder.customerOrderCode}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.receivedPerson',
                                defaultMessage: '收货联系人'
                            })}>{partSaleOrder.receivedPerson}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.partOrderPriceTerms',
                                defaultMessage: '价格条款'
                            })}>{conventEnumValueToString(partOrderPriceTerms, partSaleOrder.partOrderPriceTerms)}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.receivedPersonPhone',
                                defaultMessage: '联系电话'
                            })}>{partSaleOrder.receivedPersonPhone}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.carier',
                                defaultMessage: '指定货代'
                            })}>{partSaleOrder.carier}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.transportType',
                                defaultMessage: '运输方式'
                            })}>{conventEnumValueToString(transportType, partSaleOrder.transportType)}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.receivedPort',
                                defaultMessage: '目的港口'
                            })}>{partSaleOrder.receivedPort}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.currency',
                                defaultMessage: '币种'
                            })}>{conventEnumValueToString(currency, partSaleOrder.currency)}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.shipmentPort',
                                defaultMessage: '发运港口'
                            })}>{partSaleOrder.shipmentPort}</Description>
                        </DescriptionList>
                        <DescriptionList col="1" className={styles.detailDescriptionList}>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.receivedAddress',
                                defaultMessage: '收货地址'
                            })}>{partSaleOrder.receivedAddress}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.remark',
                                defaultMessage: '备注'
                            })}>{partSaleOrder.remark}</Description>
                        </DescriptionList>
                    </Card>
                    <Card>
                        <DescriptionList size="large" title={formatMessage({
                            id: 'detailPanel.table.other',
                            defaultMessage: '收款信息'
                        })}>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.bankAccount',
                                defaultMessage: '银行账号'
                            })}>{data.bankAccount}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.comment',
                                defaultMessage: '意见'
                            })}>{data.comment}</Description>
                        </DescriptionList>
                    </Card>
                    {(data.status === proformaInvoiceStatus.信用审核通过 || data.status === proformaInvoiceStatus.确认) &&
                    attachments && attachments.length >= 0
                        ? <Card><DescriptionList size="large" title={formatMessage({
                            id: 'detailPage.card.attachment',
                            defaultMessage: 'PI附件'
                        })}>
                            {attachments.map(item => (<Description key={item.fileId}>
                                <a icon="download" download href={`${FILES_API.files}/${item.fileId}`} size="small">
                                    {item.fileName}</a></Description>))}
                        </DescriptionList></Card>
                        : <Card><DescriptionList size="large" title={formatMessage({
                            id: 'detailPage.content.noAttachment',
                            defaultMessage: '暂无附件'
                        })}>
                        </DescriptionList></Card>}
                    <Card>
                        <DescriptionList size="large" title={formatMessage({
                            id: 'detailPanel.table.details',
                            defaultMessage: '清单'
                        })}>
                            <Table
                                className="white-space-nowrap"
                                columns={colums}
                                rowKey="id"
                                pagination={false}
                                dataSource={this.state.details}
                                rowClassName={this.setRowClassName}
                                footer={() => <DescriptionList>
                                    <Description term={formatMessage({
                                        id: 'newPanel.operation.totalAmount',
                                        defaultMessage: '总金额'
                                    })}>{formatAmount(totalAmount)}
                                    </Description>
                                    <Description term={formatMessage({
                                        id: 'newPanel.operation.totalQuantity',
                                        defaultMessage: '总数量'
                                    })}>{totalQuantity}
                                    </Description>
                                </DescriptionList>}
                                {...TABLE} />
                        </DescriptionList>
                    </Card>
                    <Card>
                        <DescriptionList size="large" title={formatMessage({
                            id: 'detailPanel.table.operateHistroies',
                            defaultMessage: '操作历史'
                        })}>
                            <Table
                                className="white-space-nowrap"
                                columns={operateHisColums}
                                rowKey="id"
                                pagination={false}
                                dataSource={this.state.data.operationHistories}
                                {...TABLE} />
                        </DescriptionList>
                    </Card>
                </Spin>
                <div className="page-toolbar">
                    <Button type="primary" onClick={this.onCancel}>{this.props.intl.formatMessage({
                        id: 'detailPanel.operation.onCancel',
                        defaultMessage: '返回'
                    })}</Button>
                </div>
            </div>
        );
    }
}

DetailPanel.propTypes = {
    history: PropTypes.object,
    id: PropTypes.string,
    intl: PropTypes.object
};

import {connect} from 'react-redux';
import {tableSearch} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = state => ({
    permissions: getPermissions(state),
});
const mapDispatchToProps = (dispatch, props) => ({
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(DetailPanel));
